package com.mfnote.view.main;

import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.baidu.oauth.BaiduOAuth;
import com.baidu.oauth.BaiduOAuth.BaiduOAuthResponse;
import com.baidu.pcs.BaiduPCSClient;
import com.baidu.pcs.BaiduPCSStatusListener;
import com.mfnote.adapter.ExpandAdapter;
import com.mfnote.adapter.MyPagerAdapter;
import com.mfnote.util.BaiduYunUtils;
import com.mfnote.db.dao.HandDao;
import com.mfnote.db.dao.MainDao;
import com.mfnote.db.dao.PaintDao;
import com.mfnote.db.dao.RecordDao;
import com.mfnote.db.dao.WriteDao;
import com.mfnote.model.Item;
import com.mfnote.model.MainCountEntity;
import com.mfnote.util.TimeUtil;
import com.mfnote.view.R;
import com.mfnote.view.R.anim;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.R.style;
import com.mfnote.view.hand.HandActivity;
import com.mfnote.view.hand.HandWritingActivity;
import com.mfnote.view.hand.NewHandActivity;
import com.mfnote.view.other.MyApplication;
import com.mfnote.view.paint.NewPaintActivity;
import com.mfnote.view.paint.PaintActivity;
import com.mfnote.view.record.NewRecordActivity;
import com.mfnote.view.record.RecordActivity;
import com.mfnote.view.setting.AboutActivity;
import com.mfnote.view.setting.OpenEncyptActivity;
import com.mfnote.view.setting.SettingActivity;
import com.mfnote.view.write.NewWriteActivity;
import com.mfnote.view.write.WriteActivity;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 主界面
 * @author ZHF
 *
 */
public class MainActivity extends Activity implements OnClickListener{
	
	public static boolean isUpdate = false; //默认不更新数据
	
	GridView gv_buttom_menu = null;
	TextView main_write_count,main_paint_count,main_hand_count,main_record_count;
	LinearLayout main_ll_write,main_ll_paint,main_ll_hand,main_ll_record,main_ll_login,main_ll_encrypt;
	
	ImageButton main_title_ib; //左上角图标
	Button mBtnRefresh = null; //刷新按钮
	TextView mTitle= null; //详情文字
	PopupWindow mPopupWindow = null;
	Button mBtnEncrypt,mBtnAbout, mBtnHelp; //加密，关于，帮助
	MainCountEntity mainCount = null;
	
	private String isEncypt = "";//获取配置文件中的密码
	public static String open = "false"; //用于标记是否已经正确输入密码
	public static  boolean isFirst = true;  //标志是否为再次进入此界面
	
	//ViewPager 
	private ViewPager mViewPager; 
	private List<View> viewList; //添加页面
	View viewMain;//主界面
	View viewDetail;//记录界面
	
	//记录详情界面
	private ExpandableListView mListView = null;
	private ExpandAdapter mAdapter = null; //适配器
	private List<List<Item>> mData = new ArrayList<List<Item>>();

	LinearLayout ll_login,ll_progress=null; //登录/进度条
	private String mbOauth,userName; // toke值/百度用户名
	private final static String mbApiKey = "PoGvMM0x2ZYfFjOX73GGp0m5"; // //用户API
	private final static String mbRootPath = "/apps"; // 文件在云端保存的位置
	private TextView tv_progress; // 在标题栏显示当前用户/显示上传进度
	SharedPreferences sp = null;
	private String tiedUser,tiedToken; // 已绑定的用户,已绑定的token
	private ProgressBar mProgress = null; // 进度条
	private int mCount,mCount2,mCount3;
	private String count,count2,count3;
	private String filePath = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/MFNote";
 	private String[] fileName = new String[] { "record", "image", 
			"notes", "hand" };
	private long totalSize,currentSize; //SD卡MFNote内文件总大小/当前已上传的大小
	final DecimalFormat df = new DecimalFormat();
	List<String> yunFiles=new ArrayList<String>();
	List<String> sdFiles=new ArrayList<String>();
	boolean flag=false;
	public static MainActivity instance;
	AlertDialog alertDialog,alertDlgUpload,alertDlgDownLoad,alertDlgTiedUser,alertDlgLoginRemind,alertDlgLoginSuccess;  //上传和下载提示对话框
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0: // 上传附件 
				if(totalSize!=0){
					double a = (double) currentSize / totalSize;
					count = df.format(100 * a);
					mCount = Integer.parseInt(count);
					Log.d("mCount", mCount+"");
					mProgress.setProgress(mCount);
					tv_progress.setText("正在上传"+ "("+ mCount+ "%)");
					if(mCount>=100){
						Toast.makeText(getApplicationContext(), "上传成功",
								Toast.LENGTH_SHORT).show();
						mCount=0;
						currentSize=0;
						count=null;
						mProgress.setProgress(0);
						tv_progress.setText("");
						ll_progress.setVisibility(View.GONE);
					}
				}
				break;
			case 1: //上传数据库
				Toast.makeText(getApplicationContext(), "上传成功",
						Toast.LENGTH_SHORT).show();
				mCount2=0;
				count2=null;
				tv_progress.setText("");
				mProgress.setProgress(0);
				ll_progress.setVisibility(View.GONE);
				break;
			case 2: //下载数据库
				Toast.makeText(getApplicationContext(), "下载成功",
						Toast.LENGTH_SHORT).show();
				mCount3=0;
				count3=null;
				tv_progress.setText("");
				mProgress.setProgress(0);
				ll_progress.setVisibility(View.GONE);
				//加载数据库
				 loadSQLData();
				//显示界面
				main_write_count.setText(String.valueOf(mainCount.getWriteCount()-1));
				main_paint_count.setText(String.valueOf(mainCount.getPaintCount()-1));
				main_hand_count.setText(String.valueOf(mainCount.getHandCount()-1));
				main_record_count.setText(String.valueOf(mainCount.getRecordCount()-1));
				break;
			}
			super.handleMessage(msg);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		instance=this;
		sp = getSharedPreferences("wpq", 0);
		tiedUser = sp.getString("UserName", "");
		tiedToken = sp.getString("MbOauth", "");
		if (tiedUser != null && !tiedUser.equals("")) {
			mbOauth = tiedToken;
		}
		Intent intent2 = getIntent();
		if(intent2.getExtras() != null) {
			open = intent2.getExtras().getString("open");
		}
		//获取配置文件信息
		SharedPreferences sharedPreferences = getSharedPreferences(
				"LoginValue", Context.MODE_WORLD_READABLE);
		// getString()第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
		isEncypt = sharedPreferences.getString("isEncypt", "false");
		
		//这里要判断一下进入输入密码界面，还是主界面
		if(isEncypt.equals("true") && isFirst == true) {
			isFirst = false;
			 Intent intent = new Intent(MainActivity.this,OpenEncyptActivity.class);
			 intent.putExtra("isEncypt", isEncypt);
			 startActivity(intent);
			 finish();
		}else if(!open.equals("")){
			setContentView(R.layout.activity_main);
		    MyApplication.getInstance().addActivity(this);
			
			//上传按钮
		    mBtnRefresh = (Button) findViewById(R.id.main_btn_refresh);
			//上传监听器
		    mBtnRefresh.setOnClickListener(this);
			//标题文字
			mTitle = (TextView) findViewById(R.id.title);
			main_title_ib = (ImageButton) findViewById(R.id.main_title_ib); //左边标题按钮
			main_title_ib.setOnClickListener(this);
			
			
			Log.i("MainActivity--->第几次调用", "onCreate");
			
			LayoutInflater mInflater = getLayoutInflater().from(this);
			viewMain = mInflater.inflate(R.layout.fragment_main, null); //主界面
		    viewDetail = mInflater.inflate(R.layout.fragment_detail, null); //记事详情
			viewList = new ArrayList<View>();
			viewList.add(viewMain);
			viewList.add(viewDetail);
			
			mViewPager = (ViewPager) findViewById(R.id.viewpager);
			mViewPager.setAdapter(new MyPagerAdapter(viewList));
			mViewPager.setCurrentItem(0);
			//设置绑定监听器
			mViewPager.setOnPageChangeListener(new mPageChangeListener(MainActivity.this, mViewPager, viewList));
			
			//加载控件
			main_write_count = (TextView) viewMain.findViewById(R.id.main_item_write_num);
			main_paint_count = (TextView) viewMain.findViewById(R.id.main_item_paint_num);
			main_hand_count = (TextView) viewMain.findViewById(R.id.main_item_hand_num);
			main_record_count = (TextView) viewMain.findViewById(R.id.main_item_record_num);
			main_ll_write = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_write);
			main_ll_paint = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_paint);
			main_ll_hand = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_hand);
			main_ll_record = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_record);
			main_ll_login = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_login);
			main_ll_encrypt = (LinearLayout) viewMain.findViewById(R.id.main_ll_item_encypt);
			
			
			//绑定监听器
			main_ll_write.setOnClickListener(this);
			main_ll_paint.setOnClickListener(this);
			main_ll_hand.setOnClickListener(this);
			main_ll_record.setOnClickListener(this);
			main_ll_login.setOnClickListener(this);
			main_ll_encrypt.setOnClickListener(this);
			
			//加载数据库
			loadSQLData();
			//显示界面
			main_write_count.setText(String.valueOf(mainCount.getWriteCount()-1));
			main_paint_count.setText(String.valueOf(mainCount.getPaintCount()-1));
			main_hand_count.setText(String.valueOf(mainCount.getHandCount()-1));
			main_record_count.setText(String.valueOf(mainCount.getRecordCount()-1));
	   }
		df.applyPattern("##0");
		totalSize=BaiduYunUtils.fileTotalSize();
		mProgress = (ProgressBar) findViewById(R.id.main_progress);
		tv_progress = (TextView) findViewById(R.id.main_tv_progress);
		ll_progress=(LinearLayout) findViewById(R.id.main_ll_progress);
		
	}
	
	/**加载数据库数据**/
	public  boolean loadSQLData() {
		//1.首次进入主界面创建五张表
		//2.后面进入主界面获取数据库，加载对应表中的数据，并显示在界面上
		
		if(!isUpdate) {
			//从数据库里获取各个表的记录数
			ArrayList<MainCountEntity> list = new MainDao(getApplicationContext()).getMainCount();
			mainCount = list.get(0);
			if(mainCount.getWriteCount() != 1 || mainCount.getPaintCount() != 1 
					|| mainCount.getHandCount() != 1 || mainCount.getRecordCount() != 1) {
				isUpdate = true;
			}
		}
		if(isUpdate) {
		    //mainCount表要更新了哦
			//获取四张表的数据
			long writeCount = new WriteDao(getApplicationContext()).queryCount();
			long paintCount = new PaintDao(getApplicationContext()).queryCount();
			long handCount = new HandDao(getApplicationContext()).queryCount();
			long recordCount = new RecordDao(getApplicationContext()).queryCount();
		    mainCount = new MainCountEntity(writeCount,paintCount,handCount,recordCount);
			//更新数据库
			new MainDao(getApplicationContext()).updateMainCount(mainCount);
		}
		return false;
		//后面跳回到主界面时在生命周期中再次调用此方法，以实现动态加载刷新数据
	}

	private long exitTime = 0; 
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ 
			if((System.currentTimeMillis()-exitTime) > 2000){ 
				Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); 
				exitTime = System.currentTimeMillis(); 
			} else { 
				MyApplication.getInstance().exit();
			} 
			return true; 
		} 
		return super.onKeyDown(keyCode, event); 
	} 
	
//	/**返回键处理**/
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if(keyCode == KeyEvent.KEYCODE_BACK) {
//			loadExitDialog();
//		}
//		return super.onKeyDown(keyCode, event);
//	}
	/**退出对话框**/
	private void loadExitDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_main_exit, null);
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDialog.setContentView(viewDialog,layoutParams);
//		Window window = alertDialog.getWindow();
//		window.setContentView(R.layout.exit_dialog,layoutParams);
//		Button exit_btn = (Button) window.findViewById(R.id.exit_btn);
//		Button cancel_btn = (Button) window.findViewById(R.id.cancel_btn);
		Button exit_btn = (Button) viewDialog.findViewById(R.id.exit_btn);
		Button cancel_btn = (Button) viewDialog.findViewById(R.id.cancel_btn);
		exit_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				MyApplication.getInstance().exit();
			}
		});
		cancel_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
	}
	
	/**所有按键处理**/
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_ll_item_write: {  //实现简单跳转  
			Intent intent = new Intent(MainActivity.this,WriteActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		case R.id.main_ll_item_paint: {
			Intent intent = new Intent(MainActivity.this,PaintActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		case R.id.main_ll_item_hand: {
			Intent intent = new Intent(MainActivity.this,HandActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		case R.id.main_ll_item_record:{
			Intent intent = new Intent(MainActivity.this,RecordActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		case R.id.main_ll_item_login:{ //用户登录
			if ((tiedUser != null && !tiedUser.equals(""))
					|| (userName != null && !userName.equals(""))) {
				showTiedDialog(); // 已绑定用户提示框
			} else {
				showLoginDialog();
			}
			break;
		}
		case R.id.main_ll_item_encypt: {
			Intent intent = new Intent(MainActivity.this,SettingActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		case R.id.main_btn_refresh: { //上传按钮
			showUploadDialog();
			break;
		}
		case R.id.main_title_ib: {
			Intent intent = new Intent(MainActivity.this,AboutActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.scale_fangda_in,
					R.anim.alpha_out);
			break;
		}
		default:
			break;
		}
	}
	
	/**菜单处理**/
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        menu.add(0, 0, 0, "下载");  
        menu.add(0, 1, 0, "退出");  
        return super.onCreateOptionsMenu(menu);  
    }  
	  @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:  //下载
			showDownloadDialog();
			break;
		case 1:  //退出
			MyApplication.getInstance().exit();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**自定义page切换监听器**/
	private  class mPageChangeListener  implements OnPageChangeListener {
		private Context mContext;
		private ViewPager mViewPager;
		private List<View> mViewLists;
		public mPageChangeListener(Context mContext, ViewPager mViewPager, List<View> mViewLists) {
			this.mContext = mContext;
			this.mViewLists = mViewLists;
			this.mViewPager = mViewPager;
		}
		/** 此方法是页面跳转完后得到调用，arg0是你当前选中的页面的Position（位置编号）。**/
		@Override
		public void onPageSelected(int arg0) {
			if(arg0 == 1) {  //记录详情界面
				View viewDetails = mViewLists.get(arg0);
//				Toast.makeText(mContext, "我是第二个界面", Toast.LENGTH_SHORT).show();
				//更换标题
				mTitle.setText("全部文件");
				//加载新的布局文件ExpandListView
				mListView = (ExpandableListView) viewDetails.findViewById(R.id.fragment_detail_exlistview);
				//每次用完记得清空，否则数据会重复
				mData.clear();
				//初始化ExpandableListView中组和子项的数据
				initData();
				//点击之后的状态变化
				//mListView.setGroupIndicator(getResources().getDrawable(R.drawable.expander_floder));
				mListView.setGroupIndicator(null);
				mAdapter = new ExpandAdapter(viewDetails.getContext(), mData); //实例化自定义适配器
			
				mListView.setAdapter(mAdapter);
				
				//设置默认展开
				for(int i = 0; i < mAdapter.getGroupCount(); i++){
					mListView.expandGroup(i);
				}
				//为list子项设置监听器
				mListView.setOnChildClickListener(new OnChildClickListener() {
					@Override
					public boolean onChildClick(ExpandableListView parent, View v,
							int groupPosition, int childPosition, long id) {
						//功能过于复杂，直接进入对应模块即可
						//获取对应数据
						String title = mData.get(groupPosition).get(childPosition).getName();
						int imgId = mData.get(groupPosition).get(childPosition).getImageId();
						
						switch(imgId) {
						case 0:  {//记事本跳转
							Intent intent = new Intent(MainActivity.this,NewWriteActivity.class);
							HashMap<String, Object> map = new WriteDao(mContext).queryByTitle(title).get(0);
							intent.putExtra("map",map);
							startActivity(intent);
							finish();
							overridePendingTransition(R.anim.scale_fangda_in,
									R.anim.alpha_out);
							break;
						}
						case 1: {//绘画跳转
							HashMap<String,Object> map= new PaintDao(mContext).queryByTitle(title).get(0);
							File file=new File((String) map.get("imagePath"));
							if(map.get("title").equals("点我开始涂鸦")||file.exists()){
								Intent intent=new Intent(MainActivity.this,NewPaintActivity.class);
								intent.putExtra("paintmap", map);
								startActivity(intent);
								finish();
								overridePendingTransition(R.anim.scale_fangda_in,
										R.anim.alpha_out);
							}else{
								Toast.makeText(mContext, "文件不存在", Toast.LENGTH_SHORT).show();
							}
							break;
						}
						case 2: { //笔迹跳转
							HashMap<String,Object> map = new HandDao(mContext).queryByTitle(title).get(0);
							//此处判断往哪里跳
							int flag = (Integer) map.get("flag");
							if(flag == 0) {
								Intent intent=new Intent(MainActivity.this,NewHandActivity.class);
								intent.putExtra("map", map);
								startActivity(intent);
								finish();
								overridePendingTransition(R.anim.scale_fangda_in,
										R.anim.alpha_out);
							}else if(flag == 1) {
								//跳往笔迹
								Intent intent=new Intent(MainActivity.this,HandWritingActivity.class);
								intent.putExtra("map", map);
								startActivity(intent);
								finish();
								overridePendingTransition(R.anim.scale_fangda_in,
										R.anim.alpha_out);
							}
							break;
						}
						case 3: { //录音跳转
							HashMap<String,Object> map = new RecordDao(mContext).queryByTitle(title).get(0);
							Intent intent=new Intent(MainActivity.this,NewRecordActivity.class);
							intent.putExtra("map", map);
							startActivity(intent);
							finish();
							overridePendingTransition(R.anim.scale_fangda_in,
									R.anim.alpha_out);
							break;
						}
					}
					return false;
				}
			});
			//此处对录详情界面进行一系列的操作
			Button fragment_detail_btn_add = (Button) viewDetails.findViewById(R.id.fragment_detail_btn_add);
			fragment_detail_btn_add.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					//弹出新建记事类型选择对话框
					loadStyleDialog(v);
				}
			});
		/*****************************主界面***********************************/
			}else if(arg0 == 0){ 
				//更换标题
				mTitle.setText("MFNote");
				//加载数据库
				loadSQLData();
				//显示界面
				main_write_count.setText(String.valueOf(mainCount.getWriteCount()-1));
				main_paint_count.setText(String.valueOf(mainCount.getPaintCount()-1));
				main_hand_count.setText(String.valueOf(mainCount.getHandCount()-1));
				main_record_count.setText(String.valueOf(mainCount.getRecordCount()-1));
			}
		}
		/**当页面在滑动的时候会调用此方法，在滑动被停止之前，此方法回一直得到
		 *arg0:当前页面，及你点击滑动的页面
         *arg1:当前页面偏移的百分比
         *arg2:当前页面偏移的像素位置   
		 * **/
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
//				System.out.println("当前卡片---》" + arg0);
		}
		/**状态变化：1滑动开始---》2滑动中----》0默认什么都没做**/
		@Override
		public void onPageScrollStateChanged(int arg0) {
//			System.out.println("状态变化------》" + arg0);
		}
	};
	
	/**记事类型选择对话框**/
	private void loadStyleDialog(View v) {
		Dialog styleDialog = new Dialog(v.getContext(), R.style.login_dialog_Dialog);
		View view = LayoutInflater.from(v.getContext()).inflate(R.layout.fragment_detail_newstyle_dialog, null);
		styleDialog.setContentView(view);
		//处理点击事件
		ImageView main_ll_item_write = (ImageView) view.findViewById(R.id.fragment_detail_newstyle_dialog_write);
		ImageView main_ll_item_paint = (ImageView) view.findViewById(R.id.fragment_detail_newstyle_dialog_paint);
		ImageView main_ll_item_hand = (ImageView) view.findViewById(R.id.fragment_detail_newstyle_dialog_hand);
		ImageView main_ll_item_record = (ImageView) view.findViewById(R.id.fragment_detail_newstyle_dialog_record);
		//设置事件
		main_ll_item_write.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,NewWriteActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.scale_fangda_in,
						R.anim.alpha_out);
			}
		});
		main_ll_item_paint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,NewPaintActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.scale_fangda_in,
						R.anim.alpha_out);
			}
		});
		main_ll_item_hand.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,NewHandActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.scale_fangda_in,
						R.anim.alpha_out);
			}
		});
		main_ll_item_record.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,NewRecordActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.scale_fangda_in,
						R.anim.alpha_out);
			}
		});
		styleDialog.show();
	}
		
	/**初始化数据**/
	private void initData() {
		/**
		 *mData的 数据格式
		 *  [
		 *  0今天：[
		 *        Item [ImageId=2130837581, name=萧峰, time=2013.09.14],
		 *        Item [ImageId=2130837585, name=段誉, time=2013.09.14]
		 *       ], 
		 *  1本周:[
		 *        Item [ImageId=2130837581, name=郭靖, time=2013.09.12], 
		 *        Item [ImageId=2130837585, name=黄蓉, time=2013.09.9],
		 *        Item [ImageId=2130837582, name=王重阳, time=2013.09.8]
		 *       ], 
		 *  2更早:[
		 *        Item [ImageId=2130837581, name=杨过, time=1991.04.15], 
		 *        Item [ImageId=2130837585, name=小龙女, time=1999.9.8]
		 *       ]
		 *   ]
		 */
		/*for(int i = 0; i < mGroupArrays.length; i++) {
			List<Item> list = new ArrayList<Item>();
			String[] childs = getStringArray(mGroupArrays[i]); //标题
			String[] details = getStringArray(mDetailIds[i]); //时间
			for(int j = 0; j < childs.length; j++) {
				Item item = new Item(mImageIds[i][j], childs[j], details[j]);
				list.add(item);
			}
			mData.add(list);   //将获取到的每一项数据对应的添加到集合中
			System.out.println(mData+"");
		}*/
		//1.从数据库里获取数据（四项;  2.之后将所有数据（标题，时间）按时间拆分，对应存储到数组和集合中
		//记事本数据
		ArrayList<HashMap<String, Object>> mData_Write = new WriteDao(viewDetail.getContext()).getWriteAllCount();
		ArrayList<HashMap<String, Object>> mData_Paint = new PaintDao(viewDetail.getContext()).getPaintAllCount();
		ArrayList<HashMap<String, Object>> mData_Hand = new HandDao(viewDetail.getContext()).getHandAllCount();
		ArrayList<HashMap<String, Object>> mData_Record = new RecordDao(viewDetail.getContext()).getRecordAllCount();
//		//调用此方法将从数据库里获取的数据按照对应格式添加
		mData = getAllInfo(mData_Write, mData_Paint, mData_Hand, mData_Record);
		
	}

	/**将数据库中获取的信息转换成对应的格式**/
	private List<List<Item>> getAllInfo(ArrayList<HashMap<String, Object>> mData_Write,ArrayList<HashMap<String, Object>> mData_Paint, 
			ArrayList<HashMap<String, Object>> mData_Hand,ArrayList<HashMap<String, Object>> mData_Record) {
		List<List<Item>> tempList = new ArrayList<List<Item>>();
		tempList.add(getAllItems(0, mData_Write)); //记事本
		tempList.add(getAllItems(1, mData_Paint));   //绘画
		tempList.add(getAllItems(2, mData_Hand));    //笔迹
		tempList.add(getAllItems(3, mData_Record));   //录音
		//对所有Item进行时间分类，装入今天，本周，更早集合中
		List<Item> todayList = new ArrayList<Item>();
		List<Item> weekList = new ArrayList<Item>();
		List<Item> beforeList = new ArrayList<Item>();
		List<List<Item>> listAll = new ArrayList<List<Item>>(); //获取最终集合
		for (int i = 0; i < tempList.size(); i++) {
			for (int j = 0; j < tempList.get(i).size(); j++) {
				String time = tempList.get(i).get(j).getTime();  //获取对应Item中的时间值
				System.out.println("--所有时间--->"+time);
				Date date = new Date(System.currentTimeMillis());  //系统当前时间
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String presentTime  = dateFormat.format(date) ;   //保存时的时间
				//获取时间差
				long timeLength = 0;
				if(time!=null && !time.equals("")) {
					try {
						timeLength = TimeUtil.compareTime(time, presentTime);
						//根据时间差存储到对应的集合中，除去
						if(timeLength == 0) {  //今天
							todayList.add(tempList.get(i).get(j));
						}else if(timeLength > 0 && timeLength <= 7) {  //本周
							weekList.add(tempList.get(i).get(j));
						}else if(timeLength > 7) {  //更早
							beforeList.add(tempList.get(i).get(j));
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
		}
		listAll.add(todayList);
		listAll.add(weekList);
		listAll.add(beforeList);
		return listAll;
	}
	
	/**公共方法：遍历集合中的数据**/
	private ArrayList<Item> getAllItems(int flag, ArrayList<HashMap<String, Object>> tempList) {
		ArrayList<Item> list = new ArrayList<Item>();
		Item mItem = null;
		
		Iterator<HashMap<String, Object>> itor = tempList.iterator();
		while(itor.hasNext()) {
			HashMap<String, Object> temMap = itor.next();
			String name = temMap.get("title").toString();
			String time = temMap.get("time").toString();
			mItem = new Item(flag, name, time);
			list.add(mItem);
		}
		return list;
	}
	
	/** 从这儿往下是百度网盘登录部分 */
	/** 百度网盘登录提示框 */
	private void showLoginDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_main_login_remind, null);
		alertDlgLoginRemind = new AlertDialog.Builder(this).create();
		alertDlgLoginRemind.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgLoginRemind.setContentView(viewDialog,layoutParams);
		Button btn_login=(Button) viewDialog.findViewById(R.id.login_btn_login);
		Button btn_cancel=(Button) viewDialog.findViewById(R.id.login_btn_cancel);
		btn_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgLoginRemind.dismiss();
				if(BaiduYunUtils.isNetwork()==true){
					login(); // 登录
				}else{
					Toast.makeText(getApplicationContext(), "登录失败,请检查网络连接",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgLoginRemind.dismiss();
			}
		});
	}
	
	/** 用户登录 */
	private void login() {
		BaiduOAuth oauthClient = new BaiduOAuth();
		oauthClient.startOAuth(this, mbApiKey, new BaiduOAuth.OAuthListener() {
			@Override
			public void onException(String msg) {
				Toast.makeText(getApplicationContext(), "登录失败,请检查网络连接",
						Toast.LENGTH_SHORT).show();
			}
			@Override
			public void onComplete(BaiduOAuthResponse response) {
				if (null != response) {
					showSuccessedDialog(); // 登录成功提示框
					userName = response.getUserName();
					mbOauth = response.getAccessToken();
					Log.d("mbOauth", mbOauth);
					BaiduYunUtils.mkdir(mbOauth);

					Editor e = sp.edit();
					e.putString("UserName", userName);
					e.putString("MbOauth", mbOauth);
					e.commit();
				}
			}
			@Override
			public void onCancel() {
				 //Toast.makeText(getApplicationContext(),"已取消登录", 0).show();
			}
		});
	}
	
	/** 百度网盘绑定成功提示框 */
	public void showSuccessedDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_main_login_success, null);
		alertDlgLoginSuccess = new AlertDialog.Builder(this).create();
		alertDlgLoginSuccess.show();
		Display display=MainActivity.instance.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgLoginSuccess.setContentView(viewDialog, layoutParams);
		Button btn_sure=(Button) viewDialog.findViewById(R.id.login_btn_success);
		btn_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgLoginSuccess.dismiss();
			}
		});
	}
	
	/** 上传数据库到百度网盘 */
	private void upload_Data() {
		
			Thread workThread = new Thread(new Runnable() {
				public void run() {
					String tmpFile ="/data/data/com.mfnote.view/databases/MFNote.db";
					String targetFileName = mbRootPath + "/mfnote/MFNote.db";
					List<String> files=new ArrayList<String>();
					files.add(targetFileName);
					BaiduPCSClient api = new BaiduPCSClient();
					api.setAccessToken(mbOauth);
					api.deleteFiles(files);
					files.clear();
					api.uploadFile(tmpFile, targetFileName,
									new BaiduPCSStatusListener() {
										@Override
										public void onProgress(long bytes,
												long total) {
											final long bs = bytes;
											final long tl = total;
											mHandler.post(new Runnable() {
												public void run() {
													double a = (double) bs / tl;
													count2 = df.format(100 * a);
													mCount2 = Integer
															.parseInt(count2);
													try {
														if (mCount2 <= 100) {
															mProgress
																	.setProgress(mCount2);
															tv_progress
																	.setText("正在上传"
																			+ "("
																			+ mCount2
																			+ "%)");
														}
														if (mCount2 >= 100) {
															mHandler.postDelayed(
																	null, 1000);
															mHandler.sendEmptyMessage(1);
														}
													} catch (Exception e) {
														e.printStackTrace();
													}
												}
											});
										}
										@Override
										public long progressInterval() {
											return 500;
										}
									});
				}
			});
			workThread.start();
	}
	
	/** 上传数据和附件提示框 */
	private void showUploadDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_main_upload, null);
		alertDlgUpload = new AlertDialog.Builder(this).create();
		alertDlgUpload.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgUpload.setContentView(viewDialog, layoutParams);
		Button btn_data = (Button) viewDialog.findViewById(R.id.upload_btn_data);
		Button btn_attach = (Button) viewDialog.findViewById(R.id.upload_btn_attach);
		Button btn_cancel = (Button) viewDialog.findViewById(R.id.upload_btn_cancel);
		btn_data.setOnClickListener(new OnClickListener() { //数据
			@Override
			public void onClick(View v) {
				alertDlgUpload.dismiss();
				if(BaiduYunUtils.isNetwork()==true){
					if (null != mbOauth) {
						ll_progress.setVisibility(View.VISIBLE);
						upload_Data();
				    } else {
				    	Toast.makeText(getApplicationContext(), "请先登录百度网盘", Toast.LENGTH_SHORT).show();
				    }
				}else{
					Toast.makeText(getApplicationContext(), "上传失败,请检查网络连接", Toast.LENGTH_SHORT).show();
				}
			}
		});
		btn_attach.setOnClickListener(new OnClickListener() { //附件
			@Override
			public void onClick(View v) {
				alertDlgUpload.dismiss();
				boolean sdcardExist = Environment.getExternalStorageState()
						.equals(android.os.Environment.MEDIA_MOUNTED);
				if (!sdcardExist) {
					Toast.makeText(MainActivity.this, "未找到SD卡",
							Toast.LENGTH_SHORT).show();
				}else{
					if(BaiduYunUtils.isNetwork()==true){
						if(null != mbOauth){
							if(totalSize==0){
								Toast.makeText(getApplicationContext(), "附件不存在", Toast.LENGTH_LONG).show();
							}else{
								ll_progress.setVisibility(View.VISIBLE);
								Toast.makeText(getApplicationContext(), "上传速度较慢，请耐心等候", Toast.LENGTH_LONG).show();
								flag=true;
								Runnable sendable=new Runnable(){
									@Override
									public void run() {
										while(flag){
											upload_Attach();
											flag=false;
										}
									}
								};
								new Thread(sendable).start();
							}
						} else {
							Toast.makeText(getApplicationContext(), "请先登录百度网盘", Toast.LENGTH_SHORT).show();
						}
					}else{
						Toast.makeText(getApplicationContext(), "上传失败,请检查网络连接", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() { //取消
			@Override
			public void onClick(View v) {
				alertDlgUpload.dismiss();
			}
		});
	}

	/** 上传附件到百度网盘 */
	private void upload_Attach() {
			BaiduPCSClient api = new BaiduPCSClient();
			api.setAccessToken(mbOauth);
				for (int i = 0; i < fileName.length; i++) {
					BaiduYunUtils.delete_YunFiles(fileName[i],yunFiles);
				}
				api.deleteFiles(yunFiles);
				yunFiles.clear();
				for (int i = 0; i < fileName.length; i++) {
					scanfolder(fileName[i]);
				}
	}
	
	/** 扫描附件上传到百度网盘 */
	private void scanfolder(final String FileName) {
		File file = new File(filePath + "/" + FileName);
		if (file.isDirectory()) { // 如果path表示的是一个目录则返回true
			File[] array = file.listFiles(); // 列出所有文件
			for (int j = 0; j < array.length; j++) {
				Log.d("nimei", j+FileName);
				final File f = array[j];
				if (f.isFile()) {// FILE TYPE
					String name = f.getName();
					String tmpFile = filePath + "/" + FileName + "/"
							+ name;
					String targetFileName = mbRootPath + "/mfnote"
							+ "/" + FileName + "/" + name;
					BaiduPCSClient api = new BaiduPCSClient();
					api.setAccessToken(mbOauth);
					api.uploadFile(tmpFile, targetFileName,
									new BaiduPCSStatusListener() {
										@Override
										public void onProgress(
												long bytes, long total) {
											final long bs=bytes; 
											final long tl=total;
											mHandler.post(new Runnable(){
								    			public void run(){
								    				if(bs==tl){
								    					currentSize=currentSize+bs;
														mHandler.sendEmptyMessage(0);
														Log.d("currentSize", currentSize+"");
								    				}
								    			}
								    		});	
										}
									});
				}else {// FOLDER TYPE
					// folderScan(f.getAbsolutePath());
				}
			}
		}
	}

	/** 下载数据库到手机MFNote应用下 */
	private void download_Data() {
		final String target ="/data/data/com.mfnote.view/databases/MFNote.db";
		File file=new File(target);
		if(file.exists()){
			file.delete();
		}	
    		Thread downThread = new Thread(new Runnable(){
				public void run() {
		    		BaiduPCSClient api = new BaiduPCSClient();
		    		api.setAccessToken(mbOauth);
		    		String source = mbRootPath + "/mfnote/MFNote.db";
		    		api.downloadFileFromStream(source, target, new BaiduPCSStatusListener(){
						@Override
						public void onProgress(long bytes, long total) {
							// TODO Auto-generated method stub
							final long bs = bytes;
							final long tl = total;
							mHandler.post(new Runnable() {
								public void run() {
									double a = (double) bs / tl;
									count3 = df.format(100 * a);
									mCount3 = Integer
											.parseInt(count3);
									try {
										if (mCount3 <= 100) {
											mProgress
													.setProgress(mCount3);
											tv_progress
													.setText("正在下载"
															+ "("
															+ mCount3
															+ "%)");
										}
										if (mCount3 >= 100) {
											mHandler.sendEmptyMessage(2);
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							});
						}
						@Override
						public long progressInterval(){
							return 100;
						}
		    		});
				}
			});
    		downThread.start();
	}
	
	/** 已绑定用户提示框 */
	private void showTiedDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_tieduser_remind, null);
		alertDlgTiedUser = new AlertDialog.Builder(this).create();
		alertDlgTiedUser.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgTiedUser.setContentView(viewDialog,layoutParams);
		TextView tv_tied_user=(TextView) viewDialog.findViewById(R.id.login_tied_user);
		Button btn_another_user = (Button) viewDialog.findViewById(R.id.btn_tieuser_another_user);
		Button btn_cancel = (Button) viewDialog.findViewById(R.id.btn_tieuser_cancel);
		if (userName == null || userName.equals("")) {
			tv_tied_user.setText("已绑定用户： " + tiedUser);
		} else {
			tv_tied_user.setText("已绑定用户： " + userName);
		}
		btn_another_user.setOnClickListener(new OnClickListener() {//切换用户
			@Override
			public void onClick(View v) {
				alertDlgTiedUser.dismiss();
				login();
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() { //取消
			@Override
			public void onClick(View v) {
				alertDlgTiedUser.dismiss();
			}
		});
	}
	
	/** 下载数据和附件提示框 */
	private void showDownloadDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_main_download, null);
		alertDlgDownLoad= new AlertDialog.Builder(this).create();
		alertDlgDownLoad.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgDownLoad.setContentView(viewDialog,layoutParams);
		Button btn_down=(Button) viewDialog.findViewById(R.id.download_btn_down);
		Button btn_cancel=(Button) viewDialog.findViewById(R.id.download_btn_cancel);
		btn_down.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgDownLoad.dismiss();
				if(BaiduYunUtils.isNetwork()==true){
					if(null != mbOauth){
						ll_progress.setVisibility(View.VISIBLE);
						download_Data();
					} else {
						Toast.makeText(getApplicationContext(), "请先登录百度网盘", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(getApplicationContext(), "下载失败,请检查网络连接", Toast.LENGTH_SHORT).show();
				}
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgDownLoad.dismiss();
			}
		});
	}
}
